<?php
/**
 * @author GhostWei
 * @date Sep 29, 2012
 */
class translator_api_youdao extends translator_abstract {
	
	protected $_url = 'http://fanyi.youdao.com/openapi.do';
	
	public function translate() {
		$response = new translator_response();
		try {
			$concept = $this->getConcept('youdao');
		} catch (Exception $e) {
			return $response->setError($e->getMessage());
		}
		$params = array(
				'keyfrom' => $concept->getAppId(),
				'key' => $concept->getAppKey(),
				'type' => 'data',
				'doctype' => 'json',
				'version' => '1.1',
				'q' => $this->getText()
		);
		$url = $this->_url . '?' . http_build_query($params);
		$data = $this->parseJson($this->get($url));
		if(!isset($data->translation) || !is_array($data->translation)) {
			return $response->setError('undefined translation from response json');
		}
		if(isset($data->errorCode) && $data->errorCode != 0) {
			return $response->setError('error code: ' . $data->errorCode);
		}
		if(!isset($data->translation[0])) {
			return $response->setResult($this->getText());
		}
		return $response->setResult($data->translation[0]);
	}
	
	protected function parseJson($data) {
		try {
			$json = @json_decode($data);
		} catch (Exception $e) {
			return new stdClass();
		}
		return is_object($json) ? $json : new stdClass();
	}
	
}

